<?php


namespace app\app\controller;

use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;
use think\Facade;
use think\Validate;

class index extends Homebase
{
    //    ------------------------------工具方法--------------------------------------------
    /**
     * @return void  判断是否登录
     */
//    public function isLogin($data)
//    {
//
//        if ($data['openid']) {
//
//            $stmt = Db::name('member')->where('openid', $data['openid'])->field('id')->find();
//            if (!$stmt) {
//                msg(2, "您未登录请去登陆", []);
//            }
//
//        } else {
//            msg(2, "您未登录请去登陆", []);
//        }
//    }

    /**
     * 请求
     * @param $url
     * @param null $data
     * @return bool|string
     */
    private function http_request($url, $data = null)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
        exit();

    }


    //    ------------------------------基本信息--------------------------------------------

    /**
     * 获取openid
     */
    public function wxLogin()
    {
        $code = $this->request->param("code");
        $appId = config('wechat.appID');
        $secret = config('wechat.AppSecret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $res = lmcurl($url);
        msg(0, "成功", $res);
    }

    /**
     * 上传图片
     */
    public function upload_img()
    {
        $files = $this->request->file('file');//获取图片
        $info = $files->move(ROOT_PATH . 'public' . '/' . 'uploads');
//        $url = '/' . 'uploads' . '/' . $info->getSaveName();
        if ($info) {

            $logo = '/' . 'uploads' . '/' . $info->getSaveName();

            $datas = $info->getInfo();

//            $img['aid'] = 1;

//            $img['uid'] = 1;

//            $img['module'] = 'cms';

            $img['path'] = $logo;

            $img['mime'] = $datas['type'];

            $img['name'] = $datas['name'];

            $img['size'] = $datas['size'];

            $img['sha1'] = $info->hash('sha1');

            $img['md5'] = $info->hash('md5');

            $img['driver'] = 'local';

            $img['create_time'] = time();

            $img['update_time'] = time();

            $img['status'] = 1;

            $img['ext'] = $info->getExtension();

            $id = Db::name('attachment')->insertGetId($img);
            //todo 关闭oss
//            if (config('is_oss') == 1) {
//                upload_local_file($id);
//            }
            $d = db('attachment')->where('id', $id)->find();

            if ($d['type'] == 1) {
                $d['path'] = conf("lm", "url") . str_replace('\\', '/', $d['path']);
            } else {
                $d['path'] = $d['path'];
            }
            msg(0, "获取成功", $d);

        } else {
            echo $files->getError();
        }
        //msg(0, "成功", $url);
    }

    /**
     * 获取手机号
     */
    public function GetPhone()
    {
        $code = $this->request->param("code");
        $tmp = getAccessToken();
        $tmptoken = json_decode($tmp);
        $token = $tmptoken->access_token;
        $data['code'] = $code;//前端获取code

        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";

        $info = $this->http_request($url, json_encode($data), 'json');

        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info);
        $code = $tmpinfo->errcode;
        $phone_info = $tmpinfo->phone_info;
        //手机号
        $phoneNumber = $phone_info->phoneNumber;
        if ($code == '0') {
            msg(0, "成功", $phoneNumber);

        } else {
            msg(-1, "失败", $phoneNumber);
        }
    }


    /**
     * @return void 保存用户信息
     */
    public function deuser()
    {
        $data = $this->request->param();

        $datas['openid'] = $data['openid'];

        $datas['reg_ip'] = $this->request->ip();

        $datas['mobile'] = $data['mobile'];

        $datas['nickname'] = $data['nickname'];

        $datas['avatarUrl'] = $data['avatarUrl'];

        $rules = [
//            'openid' => 'require',
            'mobile' => 'require',
            'nickname' => 'require',
            'avatarUrl' => 'require',
        ];
        $message = [
//            'openid.require' => 'openid必须',
            'mobile.require' => '手机必须',
            'nickname.require' => '昵称必须',
            'avatarUrl.require' => '头像必须',
        ];
        $validate = new Validate($rules, $message);
        $result   = $validate->check($data);
        if (!$result){
            msg(-1, '缺少信息', '');
        }
        $datas['status'] = 1;
        //todo 1 增加服务站扫码所属
        if ($data['belong_business_id']) {
            $datas['belong_business_id'] = $data['belong_business_id'];
        }

        $stmt = Db::name('member')->where('openid', $datas['openid'])->find();

        if ($stmt) {
            $datas['last_login_time'] = time();
            Db::name('member')->where('openid', $datas['openid'])->update($datas);

            msg(0, '查询成功', $datas);

        } else {
            $datas['create_time'] = time();

            Db::name('member')->insert($datas);

            msg(0, '新建成功', $datas);

        }
    }

    /**
     * 修改用户头像
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getUserinfoUpdateImg()
    {
        $data = $this->request->param();

        $stmt = Db::name('member')->where('openid', $data['openid'])->update(['avatarUrl' => $data['img']]);
        $user_info = Db::name('member')->where('openid', $data['openid'])->find();
        msg(0, "修改成功", $user_info);
//        if ($stmt) {
//            msg(0, "修改成功", $user_info);
//        } else {
//            msg(-1, "修改失败", []);
//        }
    }

    /**
     * 修改用户名称
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getUserinfoUpdateName()
    {

        $data = $this->request->param();
        $update_data = array(
            'mobile' => $data['mobile'],
            'nickname' => $data['name']
        );

        $stmt = Db::name('member')->where('openid', $data['openid'])->update($update_data);

        if ($stmt) {
            msg(0, "修改成功", []);
        } else {
            msg(0, "修改成功", []);
        }

    }

    /**
     * 修改用户名称
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateCreateUserInfo()
    {

        $data = $this->request->param();
        $update_data = array(
            'mobile' => $data['mobile'],
        );

        $stmt = Db::name('member')->where('openid', $data['openid'])->update($update_data);

        if ($stmt) {
            msg(0, "修改成功", []);
        } else {
            msg(0, "修改成功", []);
        }

    }




    //    ------------------------------三咕水--------------------------------------------
    //获取banner图列表
    public function getBanner()
    {
        $data = Db::name('banner')->where(['status' => 1])->order('sort')->select();
        return responseJson(0, '查询成功', $data);
    }

    //热卖推荐
    public function recommendGoods()
    {
        $data = Db::name('goods')
            ->where(['recommend' => 1, 'status' => 1, 'is_del' => 0])
            ->field('id,name,specs,img,count,price,sort')
            ->order('sort desc')
            ->limit(4)
            ->select();
        return responseJson(0, '查询成功', $data);
    }

    //获取商品分类
    public function getGoodsCate()
    {
        $where[] = ['status', '=', 1];
        $where[] = ['is_del', '=', 0];
        $data = Db::name('goods_categoty')
            ->order('sort')
            ->where($where)->select();
        return responseJson(0, '查询成功', $data);
    }

    //通过分类获取商品分页
    public function getGoodsList()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $cate = input('cate/d', 0);
        $search = input('search');
        $where[] = ['status', '=', 1];
        $where[] = ['is_del', '=', 0];
        if ($cate) {
            $where[] = ['cate_id', '=', $cate];
        }
        if ($search) {
            $where[] = ['name', 'like', '%' . $search . '%'];
        }
        $data = $this->request->param();
        if ($data['business_token']) {
            $business_token = $data['business_token'];
            $business_info = Db::name('business')
                ->where('token', $business_token)
                ->find();
            $data = Db::name('goods')
                ->where($where)
                ->order('sort desc')
                ->paginate($length, false, [
                    'page' => $page
                ])->each(function ($item) use ($business_info) {
                    $awhere[] = ['business_id', '=', $business_info['id']];
                    $awhere[] = ['goods_id', '=', $item['id']];
                    $business_car = Db::name('business_order_car')->where($awhere)->find();
                    if ($business_car) {
                        $item['add_num'] = $business_car['num'];
                    } else {
                        $item['add_num'] = 0;
                    }
                    if ($item['is_kong']==1){
                        $item['is_tt2']=1;
                    }
                    if ($item['is_water']==1){
                        $item['is_tt']=1;
                    }
                    return $item;
                });
        } else {
            $whereb[] = ['isb', '<>', 1];
            $data = Db::name('goods')
                ->where($whereb)
                ->where($where)
                ->field('id,name,specs,img,count,price,purchase_price')
                ->order('sort desc')
                ->paginate($length, false, [
                    'page' => $page
                ])->each(function ($item) {
                    $item['add_num'] = 0;
                    return $item;
                });
        }
        return responseJson(0, '查询成功', $data);
    }

    //获取商品详情
    public function goodsDetail()
    {
        $goods_id = input('goods_id');
        $data = Db::name('goods')->where('id', $goods_id)->find();
        $img_list = Db::name('goods_imgs')->field('img')->where('goods_id', $goods_id)->select();
        $data['img_list'] = $img_list;
        $data['tage'] = array(
            '品牌', '三咕水', '品牌', '三咕水'
        );
        return responseJson(0, '查询成功', $data);
    }

    /**
     * 服务站端登录
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function businessLogin()
    {
        $data = $this->request->param();
        $username = $data['username'];
        $password = $data['password'];
        $where[] = ['username', '=', $username];
        $where[] = ['password', '=', md5($password . 'business')];
        $business = Db::name('business')->where($where)->find();
        if ($business) {
            if ($business['status'] != 1) {
                msg(-1, '账号待审核', '');
            }
            $update_data = array(
                'id' => $business['id'],
                'token' => md5($business['salt'] . $business['password'] . time())
            );
            $business['token'] = $update_data['token'];
            if (!$business['qr_code']) {
                $qr_code = $this->qrcode('business_id', $business['id'], 'pages/OrCode/OrCode', 400);
                $update_data['qr_code'] = $qr_code;
                $business['qr_code'] = $qr_code;
            }
            Db::name('business')->update($update_data);
            msg(0, '登录成功', $business);
        }
        msg(-1, '登录失败', $business);
    }

    //生成小程序二维码
    public function qrcode($name, $value = 123, $page, $width = 600)
    {
        try {
            $config = [
                'app_id' => config('wechat.appID'),
                'secret' => config('wechat.AppSecret'),
            ];
            $app = Factory::miniProgram($config);
            $response = $app->app_code->getUnlimit($value, [
                'page' => $page,
                'width' => $width,
            ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->save(ROOT_PATH . 'public/uploads/drivingcode', 'qrcode' . time() . $value);
                return config('wechat.url') . '/uploads/drivingcode/' . $filename;
            }
            msg(-1, '', $response);
            return -1;
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
            return -1;
        }
    }

    /**
     * 送水员端登录
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function DeliverLogin()
    {
        $data = $this->request->param();
        $username = $data['username'];
        $password = $data['password'];
        $where[] = ['username', '=', $username];
        $where[] = ['password', '=', md5($password . 'delivery')];
        $where[] = ['is_del', '<>', 1];
        $delivery = Db::name('delivery')->where($where)->find();
        if ($delivery) {
            if ($delivery['status'] != 1) {
                msg(-1, '账号不可用', '');
            }
            $update_data = array(
                'id' => $delivery['id'],
                'token' => md5($delivery['salt'] . $delivery['password'] . time())
            );
            $delivery['token'] = $update_data['token'];
            Db::name('delivery')->update($update_data);
            msg(0, '登录成功', $delivery);
        }
        msg(-1, '登录失败', $delivery);
    }

    /**
     * 用户协议
     */
    public function getUserAgreement()
    {
        $data = config('site.user_agreement');
        msg(0, '查询成功', $data);
    }

    /**
     * 隐私协议
     */
    public function getPrivacyAgreement()
    {
        $data = config('site.privacy_agreement');
        msg(0, '查询成功', $data);
    }

    /**
     * 通过地址获取经纬度
     */
    public function getLWByAddress()
    {
        $data = $this->request->param();
        $address = getLWByAddress($data['address']);
        $address = json_decode($address, true);
        if ($address['code'] == 0) {
            msg(0, '查询完成', $address['data']);
        }
        msg(-1, '查询失败', $address);
    }

    /**
     * 腾讯地图
     */
    public function getLWByAddress2()
    {
        $data = $this->request->param();
        $address = getTencentLngLat($data['address']);

        $address = json_decode($address, true);
        if ($address['code'] == 0) {
            msg(0, '查询完成', $address['data']);
        }
        msg(-1, '查询失败', $address);
    }

    //用户级别隐私协议
    public function memberPrivacyAgreement()
    {
        msg(0, '查询完成', config('site.member_privacy_agreement'));
    }

    public function getStationName()
    {
        msg(0, '查询完成', config('site.station_name'));
    }

    //获取审核图片
    public function getStationImgShenHe()
    {
        msg(0, '查询完成', config('site.web_shenhe_img'));
    }

    public function get_web_piao_url()
    {
        msg(0, '查询完成', config('site.web_piao_url'));
    }

    public function xcxOpen()
    {
        msg(0, '查询完成', config('site.xcx_open'));
    }

    public function getConfigAdmin()
    {
        $data = $this->request->param();
        if ($data['set_name'] && isset($data['set_name'])) {
            msg(0, '查询完成', config('site.' . $data['set_name']));
        }
        msg(-1, '请输入查询内容', '');
    }

    //获取水票类型
    public function getTicketCate()
    {
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $date = Db::name('ticket_category')
            ->where($where)
            ->order('sort desc')
            ->select();
        msg(0, "查询成功", $date);
    }

    //获取每种水票购买规格
    public function getTicket()
    {
        $data = $this->request->param();
        $where[] = ['tcategory_id', '=', $data['category_id']];
        $where[] = ['is_del', '=', 0];
        $ticket_category = Db::name('ticket_category')->find($data['category_id']);
        $ticket = Db::name('water_ticket')
            ->where($where)
            ->order('price')
            ->select();
        $return_data['ticket_category'] = $ticket_category;
        $return_data['ticket'] = $ticket;
        msg(0, "查询成功", $return_data);
    }

    public function dataToTime()
    {
        $data = $this->request->param();
        if (isset($data['time']) && $data['time']) {
            msg(0, '完成', date('Y-m-d H:i', $data['time']), '');
        }
        msg(-1, '请传入正确值', '', '');
    }

    //获取广告弹窗
    public function getAd(){
        $startTimestamp = strtotime("today");
        $endTimestamp = strtotime("tomorrow") - 1;
        $where[]=['is_del','=',0];
        $where[]=['status','=',1];
        $where[]=['start_time','<=',$startTimestamp];
        $where[]=['end_time','>=',$endTimestamp];
        $business = Db::name('ad')
            ->where($where)
            ->find();
        msg(0, '查询成功', $business);
    }

    //滚动页数
    public function scrollMsg()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $business = Db::name('business')
            ->where('status', '=', 1)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['mes'] = $item['business_name'].'已上线';
                return $item;
            });
        msg(0, '查询成功', $business);
    }

    //点击送达

    //扫码核销
}